package com.prabhakar.taxiclubapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;

import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class LocationMapperActivity extends FragmentActivity {

	private static final String TAG ="LocationMapperActivity ";
	GoogleMap mMap;
	GMapV2Direction md;
	Bundle b = null;
	Geocoder geo = null;
	String dropLocation ="";
	String pickUpLocation = "";
	LatLng sourceLatlng = null;
	LatLng destinationLatlng = null;
	Button homePageButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location_mapper);

		homePageButton = (Button)findViewById(R.id.ok);
		homePageButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();  
			}
		});

		JSONObject jsonObj = null;
		b = getIntent().getExtras();
		try {
			jsonObj = new JSONObject(b.getString("bookingDetails"));
			if(jsonObj!=null){
				pickUpLocation = jsonObj.getString(Constants.PICKUP_LOCATION);
				dropLocation = jsonObj.getString(Constants.DROP_LOCATION);
				Log.v(TAG ,"dropLocation = "+dropLocation+ " pickUpLocation = "+pickUpLocation );
				Toast.makeText(this,"dropLocation# = "+dropLocation+ " pickUpLocation# = "+pickUpLocation , Toast.LENGTH_LONG).show();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if(dropLocation.length()!=0 && pickUpLocation.length()!=0){
			//get latlng for both....
			sourceLatlng = getLocationFromAddress(pickUpLocation);			
			destinationLatlng = getLocationFromAddress(dropLocation);		

			Toast.makeText(this,"sourceLatlng = "+sourceLatlng+ " destinationLatlng = "+destinationLatlng , Toast.LENGTH_LONG).show();
			Log.v(TAG ,"sourceLatlng = "+sourceLatlng+ " destinationLatlng = "+destinationLatlng );
		}else{
			Toast.makeText(this, Constants.ImProperLocations_For_GMap , Toast.LENGTH_LONG).show();
			finish();
		}

		if(sourceLatlng != null && destinationLatlng != null){
			doCallAsynTaskToShowRoute();
		}else{
			finish();
		}


	}

	/*
	 *  This method returns the latLng for the Address String..
	 */	
	private LatLng getLocationFromAddress(String address){
			
			LatLng latlng = null;
			List<Address> addressList = null;
			try {
				 Geocoder geo = new Geocoder(getApplicationContext()); 
				addressList = geo.getFromLocationName(address, 5);

				if(addressList!=null && addressList.size()>0){
					
					double lng = addressList.get(0).getLongitude();
					double lat = addressList.get(0).getLatitude();
				//	System.out.println(" GeoCode -lat >>"+lat);
				//	System.out.println(" GeoCode -lang >>"+lng);
					latlng = new LatLng(lat,lng);
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}catch(Exception e1){
				System.out.println("e1.getMessage() >>>"+e1.getMessage());
				e1.printStackTrace();
			}
			
			return latlng;
		}
	
	
	/*
	 * this method initiate the map display followed by a async call..
	 */
	private void doCallAsynTaskToShowRoute(){

		Log.v(TAG ," >>> Inside doCallAsynTaskToShowRoute <<<");

		md = new GMapV2Direction();
		mMap = ((SupportMapFragment)getSupportFragmentManager()
				.findFragmentById(R.id.the_map)).getMap();

		//	mMap.setMyLocationEnabled(true);
		mMap.getUiSettings().setZoomControlsEnabled(true);
		mMap.getUiSettings().setCompassEnabled(true);
		//	mMap.getUiSettings().setMyLocationButtonEnabled(true);
		mMap.getUiSettings().setAllGesturesEnabled(true);
		mMap.setTrafficEnabled(true);
		mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
		mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sourceLatlng, 14));
		mMap.addMarker(new MarkerOptions().position(sourceLatlng).title("Start"));
		mMap.addMarker(new MarkerOptions().position(destinationLatlng).title("End"));

		new showRoute().execute();
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.location_mapper, menu);
		return true;
	}
	
	
	/*
	 * Async Class to show Route on GMap...
	 */
	private class showRoute extends AsyncTask<Void, Void, Document>{

		Document doc;
		PolylineOptions rectLine;
		int routeLength;
		int routeTime_inMins;

		@Override
		protected Document doInBackground(Void... params) {

			try{
				doc = md.getDocument(sourceLatlng, destinationLatlng, GMapV2Direction.MODE_DRIVING);
				routeTime_inMins =(int) md.getDurationValue(doc);
				routeLength = (int) md.getMyRouteLength(doc);

				Log.v(TAG ,"time duration >>"+routeTime_inMins);
				Log.v(TAG ," routeLength >>"+routeLength);

				ArrayList<LatLng> directionPoint = md.getDirection(doc);
				rectLine = new PolylineOptions().width(8).color(Color.BLUE);

				for(int i = 0 ; i < directionPoint.size() ; i++) {	
					rectLine.add(directionPoint.get(i));
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Document result) {

			String routeTimeToBeDisplayed = Constants.getRouteTimeInStringFormat(routeTime_inMins);

			mMap.addPolyline(rectLine);
			Toast.makeText(LocationMapperActivity.this," Estimated DISTANCE IN kms >>"+routeLength , Toast.LENGTH_LONG).show();
			Toast.makeText(LocationMapperActivity.this,"Estimated TIME DURATION >>"+routeTimeToBeDisplayed , Toast.LENGTH_LONG).show();

			// call a methd here...tht show the tht show the xml now '	setContentView(R.layout.location_mapper);'  ..&& the thus show the Home button..

			// also show the success msg --here on top of mao may be as a overlay...
		}

	}		// Async-Class body ends here ...

}
